package services

import (
	"errors"
	"fmt"
	"github.com/use-go/onvif/media"
	onviftype "github.com/use-go/onvif/xsd/onvif"

	"iot-base/common/cache"
	"iot-base/common/ctrltype"

	"iot-base/common/pic"
	"main/onvifprotocol"
	//"net/http"
	//"os"
	//"time"
)

func init() {
	handlerMap["snap"] = snap
}

func snap(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error) {
	if pCmd != nil && pCmd.Params != nil {
		pThingInfo, _ := cache.GetThing(pCmd.ThingID)
		if pThingInfo != nil {
			ip := pThingInfo.GetThingParam("ip", "")
			sport := pThingInfo.GetThingParam("port", "80")
			un := pThingInfo.GetThingParam("username", "admin")
			pswd := pThingInfo.GetThingParam("pswd", "")
			addr := ip + ":" + sport
			pDev, err := onvifprotocol.CreateDevice(addr, un, pswd)
			if err == nil {

				profile, okp := pCmd.Params["profile"]
				if !okp || profile == "" {
					return nil, errors.New("profile is nil")
				}
				sprofile, _ := profile.(string)
				if sprofile == "" {
					return nil, errors.New("profile is nil")
				}
				fmt.Println("&&&&&&&&&sprofile:::", sprofile)
				snap := media.GetSnapshotUri{}
				snap.ProfileToken = onviftype.ReferenceToken(sprofile)
				resp, errr := pDev.CallMethod(snap)
				if errr != nil {
					fmt.Println("**************snap error*************", errr)
					return nil, errr
				}
				doc, errdoc := onvifprotocol.ReadRsp(resp)
				if errdoc != nil {
					fmt.Println("**************ReadRsp*************", errdoc)
					return nil, errdoc
				}

				uri := doc.FindElement("./Envelope/Body/GetSnapshotUriResponse/MediaUri/Uri")
				if uri != nil {
					suri := uri.Text()
					option := cache.GetSvrOption()
					filename, err := pic.SavePic(pCmd.ThingID, suri, pThingInfo.Thing.SName, pThingInfo.StationID,
						pThingInfo.GetStationName(), option.HttpOuterAddr+"/api/picApi/", option.Token)
					if err != nil {
						return nil, err
					}
					result := make(map[string]interface{})
					result["filename"] = filename
					return result, nil
				} else {
					fmt.Println("*****************get uri not found ********", uri)
					return nil, errors.New("uri not found")
				}
				return nil, nil

			} else {
				return nil, err
			}

		}

	}
	return nil, errors.New("params missed")
}
